<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,设计模式," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言在上一篇中我们学习了行为型模式的策略模式(Strategy Pattern)和模板模式（Template Pattern）。本篇则来学习下行为型模式的两个模式，备忘录模式(Memento Pattern)和状态模式（Memento Pattern）。 备忘录模式简介  备忘录模式(Memento Pattern)用于保存一个对象的某个状态，以便在适当的时候恢复对象，该模式属于行为型模式。其主">
<meta name="keywords" content="java,设计模式">
<meta property="og:type" content="article">
<meta property="og:title" content="Java进阶篇设计模式之十二 ---- 备忘录模式和状态模式">
<meta property="og:url" content="http://yoursite.com/2018/11/22/pancm102/index.html">
<meta property="og:site_name" content="虚无境的博客">
<meta property="og:description" content="前言在上一篇中我们学习了行为型模式的策略模式(Strategy Pattern)和模板模式（Template Pattern）。本篇则来学习下行为型模式的两个模式，备忘录模式(Memento Pattern)和状态模式（Memento Pattern）。 备忘录模式简介  备忘录模式(Memento Pattern)用于保存一个对象的某个状态，以便在适当的时候恢复对象，该模式属于行为型模式。其主">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20181122192355292.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20181122192503391.png">
<meta property="og:updated_time" content="2018-12-24T13:42:20.956Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java进阶篇设计模式之十二 ---- 备忘录模式和状态模式">
<meta name="twitter:description" content="前言在上一篇中我们学习了行为型模式的策略模式(Strategy Pattern)和模板模式（Template Pattern）。本篇则来学习下行为型模式的两个模式，备忘录模式(Memento Pattern)和状态模式（Memento Pattern）。 备忘录模式简介  备忘录模式(Memento Pattern)用于保存一个对象的某个状态，以便在适当的时候恢复对象，该模式属于行为型模式。其主">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20181122192355292.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/11/22/pancm102/"/>






  <title>Java进阶篇设计模式之十二 ---- 备忘录模式和状态模式 | 虚无境的博客</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?39c177d10f6e05ddfa113e02139b9c1c";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">虚无境的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/11/22/pancm102/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="虚无境">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/xuwujing.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="虚无境的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java进阶篇设计模式之十二 ---- 备忘录模式和状态模式</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-22T19:32:01+08:00">
                2018-11-22
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="\assets\js\APlayer.min.js"> </script><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>在<a href="https://www.cnblogs.com/xuwujing/p/9873514.html" target="_blank" rel="external">上一篇</a>中我们学习了行为型模式的策略模式(Strategy Pattern)和模板模式（Template Pattern）。本篇则来学习下行为型模式的两个模式，备忘录模式(Memento Pattern)和状态模式（Memento Pattern）。</p>
<h2 id="备忘录模式"><a href="#备忘录模式" class="headerlink" title="备忘录模式"></a>备忘录模式</h2><p><strong>简介</strong></p>
<blockquote>
<p>备忘录模式(Memento Pattern)用于保存一个对象的某个状态，以便在适当的时候恢复对象，该模式属于行为型模式。<br>其主要目的是在不破坏封装性的前提下，捕获一个对象的内部状态，并在该对象之外保存这个状态。</p>
</blockquote>
<p>备忘录模式，其主要的的思想就是备份。例如，txt、word等文档的保存，游戏的存档，操作系统的备份，也包括我们经常用的快捷键Ctrl+Z等等。除了以上的这些应用，我们在编程中接触最多的估计就是数据库的事物了，它提供了一种恢复机制，可在出现异常的时候进行还原。</p>
<p><strong>备忘录模式</strong>主要由这三个角色组成，备忘录角色(Memento)、发起人角色(Originator)和负责人(Caretaker)角色。</p>
<ul>
<li>备忘录(Memento)：主要的功能是包含要被恢复的对象的状态。</li>
<li>发起人(Originator)：在创建的时候，会在备忘录对象中存储状态。</li>
<li>负责人(Caretaker)：主要是负责从备忘录对象中恢复对象的状态。</li>
</ul>
<p>示例图如下:<br><img src="https://img-blog.csdnimg.cn/20181122192355292.png" alt="在这里插入图片描述"></p>
<p>我们这里依旧用一个示例来进行说明吧。<br>我们在玩游戏有的时候，会经常用到一个游戏功能，那就是存档。主要是为了保存游戏进度，防止信息丢失，并且也可以通过进行读档恢复保存的信息。比如xuwujing在玩一个游戏的时候，创建好角色之后进行打怪练级，然后挑战BOSS，不过担心挑战失败，于是便在挑战前进行存档，存档成功之后，再来进行挑战BOSS。<br>那么我们可以根据这个场景来使用备忘录模式来进行开发。</p>
<p>首先定义一个Memento，也就是游戏存档的信息，主要存储游戏人物等级和生命值。</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"> </div><div class="line">class SaveMsg&#123;</div><div class="line">	private  int level;</div><div class="line">	private int life;</div><div class="line">		</div><div class="line">	public SaveMsg( int level, int life) &#123;</div><div class="line">		super();</div><div class="line">		this.level = level;</div><div class="line">		this.life = life;</div><div class="line">	&#125;</div><div class="line">	public int getLevel() &#123;</div><div class="line">		return level;</div><div class="line">	&#125;</div><div class="line">	public void setLevel(int level) &#123;</div><div class="line">		this.level = level;</div><div class="line">	&#125;</div><div class="line">	public int getLife() &#123;</div><div class="line">		return life;</div><div class="line">	&#125;</div><div class="line">	public void setLife(int life) &#123;</div><div class="line">		this.life = life;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后再定义一个Originator，这里就是玩家了，除了等级和生命值信息外，玩家还可以进行存档、读档，以及进行一些活动，打怪练级和挑战BOSS。</p>
<p>那么代码如下:</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line">class Player &#123;</div><div class="line">	//等级</div><div class="line">	private  int level;</div><div class="line">	//生命值</div><div class="line">	private int life;</div><div class="line"></div><div class="line">	public Player( int level, int life) &#123;</div><div class="line">		super();</div><div class="line">		this.level = level;</div><div class="line">		this.life = life;</div><div class="line">	&#125;</div><div class="line">	//保存信息</div><div class="line">	public SaveMsg saveStateToMemento() &#123;</div><div class="line">		return new SaveMsg(level,life);</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	//恢复信息</div><div class="line">	public void getStateFromMemento(SaveMsg sm) &#123;</div><div class="line">		this.level = sm.getLevel();</div><div class="line">		this.life = sm.getLife();</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	//获取当前状态</div><div class="line">	public void getStatus() &#123;</div><div class="line">		System.out.println(&quot;玩家xuwujing当前信息:&quot;);</div><div class="line">		System.out.println(&quot;人物等级:&quot;+level+&quot;,人物生命:&quot;+life);</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	//练级</div><div class="line">	public void leveling() &#123;</div><div class="line">		this.level = this.level+1;</div><div class="line">		this.life = this.life+10;</div><div class="line">		System.out.println(&quot;恭喜玩家xuwujing升级!等级提升了1,生命提升了10！&quot;);</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	//挑战BOSS</div><div class="line">	public boolean challengeBOSS() &#123;</div><div class="line">		//设置条件</div><div class="line">		return this.level&gt;2&amp;&amp;this.life&gt;100;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>最后在定义一个Caretaker，作为游戏存档页，用于保存存档信息。<br>代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">class GameSavePage&#123;</div><div class="line">	private SaveMsg sm;</div><div class="line"></div><div class="line">	public SaveMsg getSm() &#123;</div><div class="line">		return sm;</div><div class="line">	&#125;</div><div class="line">	public void setSm(SaveMsg sm) &#123;</div><div class="line">		this.sm = sm;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>编写好之后，那么我们来进行测试。</p>
<p>相应的测试代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></td><td class="code"><pre><div class="line">	public static void main(String[] args) &#123;</div><div class="line">  		int level = 1;</div><div class="line">		int life = 100;</div><div class="line">		//创建一个玩家</div><div class="line">		Player player =new Player(level, life);</div><div class="line">		System.out.println(&quot;玩家xuwujing进入游戏!&quot;);</div><div class="line">		//状态</div><div class="line">		player.getStatus();</div><div class="line">		//进行练级</div><div class="line">		player.leveling();</div><div class="line">		GameSavePage savePage =new GameSavePage();</div><div class="line">		//状态</div><div class="line">		player.getStatus();</div><div class="line">		System.out.println(&quot;玩家xuwujing正在存档...&quot;);</div><div class="line">		//第一次存档</div><div class="line">		savePage.setSm(player.saveStateToMemento());</div><div class="line">		System.out.println(&quot;玩家xuwujing存档成功!&quot;);</div><div class="line">		System.out.println(&quot;玩家xuwujing挑战新手村的BOSS!&quot;);</div><div class="line">		 boolean flag=player.challengeBOSS();</div><div class="line">		if(flag) &#123;</div><div class="line">			System.out.println(&quot;玩家xuwujing挑战BOSS成功!&quot;);</div><div class="line">			return;</div><div class="line">		&#125;</div><div class="line">		System.out.println(&quot;玩家xuwujing挑战BOSS失败!游戏结束！开始读取存档...&quot;);</div><div class="line">		savePage.getSm();</div><div class="line">		System.out.println(&quot;玩家xuwujing读取存档成功!&quot;);</div><div class="line">		//进行练级</div><div class="line">		player.leveling();</div><div class="line">		//状态</div><div class="line">		player.getStatus();</div><div class="line">		System.out.println(&quot;玩家xuwujing挑战新手村的BOSS!&quot;);</div><div class="line">		flag=player.challengeBOSS();</div><div class="line">		if(flag) &#123;</div><div class="line">			System.out.println(&quot;玩家xuwujing挑战BOSS成功!&quot;);</div><div class="line">			return;</div><div class="line">		&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>输出结果:</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">		玩家xuwujing进入游戏!</div><div class="line">玩家xuwujing当前信息:</div><div class="line">人物等级:1,人物生命:100</div><div class="line">恭喜玩家xuwujing升级!等级提升了1,生命提升了10！</div><div class="line">玩家xuwujing当前信息:</div><div class="line">人物等级:2,人物生命:110</div><div class="line">玩家xuwujing正在存档...</div><div class="line">玩家xuwujing存档成功!</div><div class="line">玩家xuwujing挑战新手村的BOSS!</div><div class="line">玩家xuwujing挑战BOSS失败!游戏结束！开始读取存档...</div><div class="line">玩家xuwujing读取存档成功!</div><div class="line">恭喜玩家xuwujing升级!等级提升了1,生命提升了10！</div><div class="line">玩家xuwujing当前信息:</div><div class="line">人物等级:3,人物生命:120</div><div class="line">玩家xuwujing挑战新手村的BOSS!</div><div class="line">玩家xuwujing挑战BOSS成功!</div></pre></td></tr></table></figure></p>
<p><strong>备忘录模式优点</strong></p>
<blockquote>
<p> 给用户提供了一种可以恢复状态的机制，可以使用户能够比较方便地回到某个历史的状态；<br> 实现了信息的封装，使得用户不需要关心状态的保存细节；</p>
</blockquote>
<p><strong>备忘录模式缺点</strong></p>
<blockquote>
<p>非常的消耗资源；<br>客户端必须知道所有的策略类才能进行调用；</p>
</blockquote>
<p><strong>使用场景：</strong> </p>
<blockquote>
<p>需要保存/恢复数据的相关状态场景；</p>
</blockquote>
<h2 id="状态模式"><a href="#状态模式" class="headerlink" title="状态模式"></a>状态模式</h2><p><strong>简介</strong></p>
<blockquote>
<p>状态模式（State Pattern）属于行为型模式，其状态的对象和一个行为随着状态对象改变而改变。<br>其主要目的解决的是当控制一个对象状态转换的条件表达式过于复杂是的情况。把状态的判断逻辑转移到表示不同状态一系列类中，可以把复杂的判断简单化。</p>
</blockquote>
<p>状态模式，其主要的的思想就是提供一种状态，提供给客户端进行调用。状态可谓无处不在，无论是电脑、手机等电子产品的开机和关机的状态，还是经常用到的网络在线和离线状态，即使是在我们编程中Tcp也有创建、监听、关闭状态。</p>
<p><strong>状态模式</strong>主要由环境角色（Context）、 抽象状态（State）和具体状态（Concrete State）组成。</p>
<ul>
<li><p>环境角色（Context）: 它定义了客户程序需要的接口并维护一个具体状态角色的实例，将与状态相关的操作委托给当前的具体状态对象来处理。</p>
</li>
<li><p>抽象状态角色(State): 定义一个接口以封装使用上下文环境的的一个特定状态相关的行为。</p>
</li>
<li>具体状态角色（Concrete State）:实现抽象状态定义的接口。 </li>
</ul>
<p>示例图如下:<br><img src="https://img-blog.csdnimg.cn/20181122192503391.png" alt="在这里插入图片描述"></p>
<p>这里为了方便理解，我们依旧使用一个简单的示例来加以说明。<br>我们在使用耳机听音乐的时候，一般会有两个状态，播放和暂停，按一下是从暂停到播放，再按一下就是从播放到暂停。那么我们可以根据这个场景来使用状态模式进行开发！</p>
<p>首先依旧定义一个抽象状态角色，用于表示音乐的状态，并指定该类的行为，也就是方法，这个抽象类的代码如下:</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">interface MusicState&#123;</div><div class="line">	void press();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>定义好该抽象类之后，我们再来定义具体状态角色类。这里定义两个状态，一个是播放状态，一个是暂停状态，代码如下:</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">class PlayState implements MusicState&#123;</div><div class="line"></div><div class="line">	@Override</div><div class="line">	public void press() &#123;</div><div class="line">		System.out.println(&quot;播放音乐!&quot;);</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">class PauseState implements MusicState&#123;</div><div class="line"></div><div class="line">	@Override</div><div class="line">	public void press() &#123;</div><div class="line">		System.out.println(&quot;暂停音乐!&quot;);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后在来定义一个环境角色，用于对客户端提供一个接口，并对状态进行处理。代码如下:</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line">class Headset&#123;</div><div class="line">	private MusicState state;</div><div class="line">	private int i;</div><div class="line">	public Headset(MusicState state)&#123;</div><div class="line">		this.state=state;</div><div class="line">	&#125;</div><div class="line">	public void press() &#123;</div><div class="line">		if((i&amp;1)==0) &#123;</div><div class="line">			this.state=new PlayState();</div><div class="line">		&#125;else &#123;</div><div class="line">			this.state=new PauseState();</div><div class="line">		&#125;</div><div class="line">		this.state.press();</div><div class="line">		i++;</div><div class="line">	&#125;</div><div class="line">	public MusicState getState() &#123;</div><div class="line">		return state;</div><div class="line">	&#125;</div><div class="line">	public void setState(MusicState state) &#123;</div><div class="line">		this.state = state;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>最后再来进行测试，测试代码如下:</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"> </div><div class="line">public static void main(String[] args) &#123;</div><div class="line">		Headset hs = new Headset(new PlayState());</div><div class="line">		//第一次播放音乐</div><div class="line">		hs.press();</div><div class="line">		//第二次暂停音乐</div><div class="line">		hs.press();</div><div class="line">		//第三次播放音乐</div><div class="line">		hs.press();</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>输出结果:</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">播放音乐!</div><div class="line">暂停音乐!</div><div class="line">播放音乐!</div></pre></td></tr></table></figure>
<p><strong>状态模式优点：</strong></p>
<blockquote>
<p>扩展性好，将和状态有关的行为放到一起，增加新的的状态，只需要改变对象状态即可改变对象的行为即可；<br>复用性好，让多个环境对象共享一个状态对象，从而减少系统中对象的个数；</p>
</blockquote>
<p><strong>状态模式缺点：</strong></p>
<blockquote>
<p>使用状态模式会增加系统类和对象的个数，并且该模式的结构与实现都较为复杂，如果使用不当将导致程序结构和代码的混乱；<br>状态模式对”开闭原则”的支持并不太好，对于可以切换状态的状态模式，增加新的状态类需要修改那些负责状态转换的源代码，否则无法切换到新增状态，而且修改某个状态类的行为也需修改对应类的源代码。</p>
</blockquote>
<p><strong>使用场景：</strong> </p>
<blockquote>
<p>行为随状态改变而改变的场景；<br>条件、分支语句的代替者。</p>
</blockquote>
<p><strong>注意事项 ：</strong> </p>
<blockquote>
<p>在行为受状态约束的时候使用状态模式，而且状态不超过5个。</p>
</blockquote>
<p><strong> 和策略模式比较：</strong><br>在学习状态模式的时候，很容易和策略模式搞混，因为它们实在是太像了，很难区分，在查阅一番资料之后，整理了如下的相同点和区别点。</p>
<p><strong>相同点:</strong></p>
<ol>
<li>它们很容易添加新的状态或策略，而且不需要修改使用它们的Context对象。</li>
<li>它们都符合OCP原则，在状态模式和策略模式中，Context对象对修改是关闭的，添加新的状态或策略，都不需要修改Context。</li>
<li>它们都会初始化。</li>
<li>它们都依赖子类去实现相关行为。</li>
</ol>
<p><strong>区别点</strong></p>
<ol>
<li>状态模式的行为是平行性的，不可相互替换的；</li>
<li>而策略模式的行为是平等性的，是可以相互替换的。</li>
<li>最重要的一个不同之处是，策略模式的改变由客户端完成；</li>
<li>而状态模式的改变，由环境角色或状态自己.</li>
</ol>
<h2 id="其它"><a href="#其它" class="headerlink" title="其它"></a>其它</h2><h3 id="音乐推荐"><a href="#音乐推荐" class="headerlink" title="音乐推荐"></a>音乐推荐</h3><p>分享一首非常有感触的轻音乐，虽然孤独，但是不寂寞！</p>
<p>网易云网友评论:</p>
<blockquote>
<p>轻吟一句情话，执笔一副情画。 绽放一地情花，覆盖一片青瓦。 共饮一杯清茶，同研一碗青砂。<br>挽起一面轻纱，看清天边月牙。爱像水墨青花，何惧刹那芳华。</p>
</blockquote>
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=139718&auto=0&height=66"></iframe>

<h3 id="项目的代码"><a href="#项目的代码" class="headerlink" title="项目的代码"></a>项目的代码</h3><p> <a href="https://github.com/xuwujing/java-study" target="_blank" rel="external">java-study </a>是本人在学习Java过程中记录的一些代码，也包括之前博文中使用的代码。如果感觉不错，希望顺手给个start，当然如果有不足，也希望提出。<br>github地址:  <a href="https://github.com/xuwujing/java-study" target="_blank" rel="external">https://github.com/xuwujing/java-study</a></p>
<p>原创不易，如果感觉不错，希望给个推荐！您的支持是我写作的最大动力！<br>版权声明:<br>作者：虚无境<br>博客园出处：<a href="http://www.cnblogs.com/xuwujing" target="_blank" rel="external">http://www.cnblogs.com/xuwujing</a><br>CSDN出处：<a href="http://blog.csdn.net/qazwsxpcm" target="_blank" rel="external">http://blog.csdn.net/qazwsxpcm</a>　<br>个人博客出处：<a href="http://www.panchengming.com" target="_blank" rel="external">http://www.panchengming.com</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>
     
    <div>
	 +
	  
<div style="text-align:center;color: #ccc;font-size:14px;">
------ 本文结束 ------</div>
<br/>
<div style="border: 1px solid black">
<div style="margin-left:10px">
<span style="font-weight:blod">版权声明</span>
<!-- <img src="/images/xuwujing.png" > -->
<br/>
<p style="font-size: 10px;line-height: 30px"><a href="http://www.panchengming.com/" style="color:#258FC6">xuwujing's Notes</a> by <a href="http://www.panchengming.com/" style="color:#258FC6">ChengMing Pan</a> is licensed under a <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/" style="color:#258FC6">Creative Commons BY-NC-ND 4.0 International License</a>.<br/>
由<a href="http://www.panchengming.com/" style="color:#258FC6">虚无境</a>创作并维护的<a href="http://www.panchengming.com/" style="color:#258FC6">xuwujing's Notes</a>博客采用<a href="https://creativecommons.org/licenses/by-nc-nd/4.0/" style="color:#258FC6">创作共用保留署名-非商业-禁止演绎4.0国际许可证</a>。<br/>
本文首发于<a href="http://www.panchengming.com/" style="color:#258FC6">xuwujing's Notes</a> 博客（ <a href="http://www.panchengming.com/" style="color:#258FC6">http://www.panchengming.com/</a> ），版权所有，侵权必究。</p>
</div>
</div>

	
	</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/设计模式/" rel="tag"># 设计模式</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/13/pancm101/" rel="next" title="Java进阶篇设计模式之十一 ---- 策略模式和模板方法模式">
                <i class="fa fa-chevron-left"></i> Java进阶篇设计模式之十一 ---- 策略模式和模板方法模式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/29/pancm103/" rel="prev" title="Java进阶篇设计模式之十三 ---- 观察者模式和空对象模式">
                Java进阶篇设计模式之十三 ---- 观察者模式和空对象模式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/xuwujing.png"
               alt="虚无境" />
          <p class="site-author-name" itemprop="name">虚无境</p>
           
              <p class="site-description motion-element" itemprop="description">The way of the future!</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">136</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">30</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">59</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xuwujing" target="_blank" title="github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  github
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/qazwsxpcm?viewmode=list" target="_blank" title="csdn">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  csdn
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://home.cnblogs.com/u/xuwujing/" target="_blank" title="cnblogs">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  cnblogs
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.woainia.site/" title="woainia" target="_blank">woainia</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="chenssy" target="_blank">chenssy</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://italker.imisty.cn" title="xiaowu" target="_blank">xiaowu</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#备忘录模式"><span class="nav-number">2.</span> <span class="nav-text">备忘录模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态模式"><span class="nav-number">3.</span> <span class="nav-text">状态模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其它"><span class="nav-number">4.</span> <span class="nav-text">其它</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#音乐推荐"><span class="nav-number">4.1.</span> <span class="nav-text">音乐推荐</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#项目的代码"><span class="nav-number">4.2.</span> <span class="nav-text">项目的代码</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">虚无境</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
 | 
本站总访问量<span id="busuanzi_value_site_pv"></span>次
 | 
本站访客数<span id="busuanzi_value_site_uv"></span>人次
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=857896&auto=0&height=66"></iframe>



        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
